﻿using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System;
using Fx.ClientProfile.Utility.Logging;

namespace Fx.Serialization
{
    /// <summary>
    /// Encapsulates how to serialize an object using BinaryFormatter.
    /// </summary>
    public class BinarySerializer
    {
        public T Deserialize<T>(string fullFilePath) where T : class
        {
            var formatter = new BinaryFormatter();
            try
            {
                using (var fs = new FileStream(fullFilePath, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    var cache = formatter.Deserialize(fs);
                    return cache as T;
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
            return null;
        }

        public void Serialize(string fullFilePath, object graph)
        {
            var formatter = new BinaryFormatter();
            try
            {
                using (var fs = new FileStream(fullFilePath, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
                {
                    formatter.Serialize(fs, graph);
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }
    }
}
